package com.gxitsky.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.databind.type.TypeFactory;

import java.util.List;

/**
 * @author gxing
 * @desc Jackson 工具类
 * @date 2022/5/23
 */
public class JSON {

    private final static ObjectMapper mapper = new ObjectMapper();
    private final static TypeFactory typeFactory = mapper.getTypeFactory();

    static {
        mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    }

    /**
     * @param obj 入参
     * @desc 对象转 Json String
     * @author gxing
     * @date 2022/5/23 17:34
     */
    public static String toJsonString(Object obj) throws JsonProcessingException {
        return mapper.writeValueAsString(obj);
    }

    /**
     * @param text 入参
     * @desc Json String 转对象
     * @author gxing
     * @date 2022/5/23 17:34
     */
    public static <T> T parseObject(String text, Class<T> type) throws JsonProcessingException {
        return mapper.readValue(text, type);
    }

    /**
     * @param text 入参
     * @desc Json String 转数组
     * @author gxing
     * @date 2022/5/23 17:34
     */
    public static <T> T parseArray(String text, Class<T> type) throws JsonProcessingException {
        return mapper.readValue(text, type);
    }

    /**
     * @param text 入参
     * @desc Json String 转 List
     * @author gxing
     * @date 2022/5/23 17:34
     */
    public static <T> T parseList(String text, TypeReference<T> valueTypeRef) throws JsonProcessingException {
        return mapper.readValue(text, valueTypeRef);
    }

    /**
     * @param text 入参
     * @desc Json String 转 List
     * @author gxing
     * @date 2022/5/23 17:34
     */
    public static <T> List<T> parseList(String text, Class<T> elementClass) throws JsonProcessingException {
        CollectionType type = typeFactory.constructCollectionType(List.class, elementClass);
        return mapper.readValue(text, type);
    }
}
